//
//  UserInfoViewController.m
//  HotWord
//
//  Created by 2013 on 7/24/12.
//  Copyright (c) 2013 __MyCompanyName__. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UserHeadInfoCell.h"
#import "UserInfoCell.h"
#import "InboxViewController.h"
#import "PeopleNearViewController.h"
#import "ServiceHelper.h"
#import "MessageManager.h"
#import "ITTImageCacheManager.h"
#import "UserManager.h"
#import "DreamSchoolViewController.h"
#import "LookingForViewController.h"
#import "ConversationViewController.h"
#import "PeopleDreamSchoolViewController.h"
#import "SliderBtn.h"
#import "MajorRankingViewController.h"


#define MAX_KEYBOARD_HEIGHT  252

@interface UserInfoViewController () <UITableViewDelegate, UITableViewDataSource, UserHeadInfoCellDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIGestureRecognizerDelegate, UIPickerViewDelegate, UIPickerViewDataSource,ITTImageViewDelegate, LookingForViewControllerDelegate,MajorRankingViewControllerDelegate>
{
    UserHeadInfoCell *_headInfoCell;
    HotWordUserUpdateType _updateType;
    UITextField *_activeField;
    UILabel *_activeLabel;
    User *_tempUser;
    
    BOOL _isEditing;
    BOOL _hasChanged;
    BOOL _isFriendInfo;
    
    NSInteger _headSelectIndex;
    SliderBtn *_sliderBtn;
}

@property (retain, nonatomic) IBOutlet UIButton *backBtn;
@property (retain, nonatomic) IBOutlet UIButton *inboxBtn;
@property (retain, nonatomic) IBOutlet UIButton *friendBtn;
@property (retain, nonatomic) IBOutlet UIPickerView *dataSelectPicker;
@property (retain, nonatomic) IBOutlet UIView *pickContainerView;
@property (retain, nonatomic) IBOutlet UIButton *editBtn;
@property (retain, nonatomic) IBOutlet UIImageView *fadeImageView;

@property (retain, nonatomic) IBOutlet UIScrollView *userInfoContainerScrollView;
@property (retain, nonatomic) IBOutlet UILabel *nickNameLabel;
@property (retain, nonatomic) IBOutlet ITTImageView *firstHeaderImageView;
@property (retain, nonatomic) IBOutlet ITTImageView *secondHeaderImageView;
@property (retain, nonatomic) IBOutlet ITTImageView *thirdHeaderImageView;
@property (retain, nonatomic) IBOutlet UIButton *genderBtn;
@property (retain, nonatomic) IBOutlet UILabel *genderLabel;
@property (retain, nonatomic) IBOutlet UIButton *ageBtn;
@property (retain, nonatomic) IBOutlet UILabel *ageLabel;
@property (retain, nonatomic) IBOutlet UILabel *studentLabel;
@property (retain, nonatomic) IBOutlet UILabel *teacherLabel;
@property (retain, nonatomic) IBOutlet UIImageView *studentMarkImageView;
@property (retain, nonatomic) IBOutlet UIImageView *teacherMarkImageView;
@property (retain, nonatomic) IBOutlet UIButton *identityBtn;
@property (retain, nonatomic) IBOutlet UILabel *testCategoryLabel;
@property (retain, nonatomic) IBOutlet UIButton *testBtn;
@property (retain, nonatomic) IBOutlet UILabel *testLabel;
@property (retain, nonatomic) IBOutlet UIButton *applyBtn;
@property (retain, nonatomic) IBOutlet UILabel *applyYearLabel;
@property (retain, nonatomic) IBOutlet UIView *marjoyContainerView;
@property (retain, nonatomic) IBOutlet UIButton *marjoyBtn;
@property (retain, nonatomic) IBOutlet UILabel *marjoyLabel;
@property (retain, nonatomic) IBOutlet UILabel *locationCategoryLabel;
@property (retain, nonatomic) IBOutlet UITextField *countryTextField;
@property (retain, nonatomic) IBOutlet UIView *countryEditBackgroundView;
@property (retain, nonatomic) IBOutlet UILabel *schoolOrCompanyLabel;
@property (retain, nonatomic) IBOutlet UIView *schoolOrCompanyEditBgView;
@property (retain, nonatomic) IBOutlet UIView *locationContainerView;
@property (retain, nonatomic) IBOutlet UIView *locationOrSchoolContainerView;
@property (retain, nonatomic) IBOutlet UILabel *cityValueLabel;
@property (retain, nonatomic) IBOutlet UILabel *schoolOrCompanyValueLabel;
@property (retain, nonatomic) IBOutlet UITextField *schoolOrCompanyTextField;
@property (retain, nonatomic) IBOutlet UIView *lookingForContainerView;
@property (retain, nonatomic) IBOutlet UIButton *lookingForBtn;
@property (retain, nonatomic) IBOutlet UILabel *lookForLabel;
@property (retain, nonatomic) IBOutlet UIView *signatureContainerView;
@property (retain, nonatomic) IBOutlet UITextView *signatureTextView;
@property (retain, nonatomic) IBOutlet UIView *editContainerView;

@property (retain, nonatomic) IBOutlet UIButton *talkBtn;
@property (retain, nonatomic) IBOutlet UIView *enlargeImageContainer;
@property (retain, nonatomic) IBOutlet UIImageView *enlargeImageView;
@property (retain, nonatomic) IBOutlet UIImageView *userTypeImageView;


@property (assign, nonatomic) BOOL isStudent;
@property (retain, nonatomic) NSDictionary *testCategoryDic;


@end

@implementation UserInfoViewController


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithUser:(User *)user
{
    self = [super init];
    if (self)
    {
        _tempUser = [user retain];
        _isFriendInfo = YES;
        if ([_tempUser.userId isEqualToString:[UserManager sharedManager].currentUser.userId])
        {
            _isFriendInfo = NO;
        }
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
        
    self.backBtn.alpha = 0;
    self.inboxBtn.alpha = 0;
    self.friendBtn.alpha = 0;
    [self.view insertSubview:_userInfoContainerScrollView belowSubview:_fadeImageView];
    self.userInfoContainerScrollView.height = self.view.height;
    self.userInfoContainerScrollView.top = self.view.height;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hanldTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];

    [self receiveMessageNotification];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessageNotification) name:NOTIFICATION_RECEIVE_MESSAGE object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    _sliderBtn = (SliderBtn *)[[[[NSBundle mainBundle] loadNibNamed:@"SliderBtn" owner:self options:nil] objectAtIndex:0] retain];
    [self.view addSubview:_sliderBtn];
    
    _friendBtn.hidden = YES;
    _inboxBtn.hidden = YES;

    if (_isFriendInfo)
    {
//        _inboxBtn.hidden = YES;
//        _friendBtn.hidden = YES;
        _talkBtn.hidden = NO;
        _sliderBtn.hidden = YES;
        _backBtn.hidden = NO;
    }
    else
    {
//        _inboxBtn.hidden = NO;
//        _friendBtn.hidden = NO;
        _talkBtn.hidden = YES;

        _tempUser = [[User alloc] init];
        [_tempUser copyFromUser:[UserManager sharedManager].currentUser];
//        [self checkUpdateUserInfoNotification];
        _sliderBtn.hidden = NO;
        _backBtn.hidden = YES;
    }
    
    _editContainerView.hidden = _isFriendInfo;
//    if (_isFriendInfo)
//    {
//        [self getFriendInfo];
//    }
    [self setUserInfo];
    [self updatEditStatus];

}


- (void)getFriendInfo
{
    User *cacheUser = [[UserManager sharedManager] getCacheUser:_tempUser.userId];
    if (!cacheUser) {
        [[HTActivityIndicator currentIndicator] displayActivity:@"Getting Profile..."];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        if (_tempUser.userId)
        {
            [params setObject:_tempUser.userId forKey:@"id"];
        }
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetUserInfo WithParameters:params AndCallBackScope:self AndSuccessSel:@"getUserInfoSuccess:" AndFailedSel:@"getUserInfoFailed:"];
    }
    else
    {
        if (_tempUser)
        {
            RELEASE_SAFELY(_tempUser);
        }
        _tempUser = [cacheUser retain];
    }

}

- (void)getUserInfoSuccess:(NSObject *)result
{
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        User *user = [[[User alloc] init] autorelease];
        user.userId = _tempUser.userId;
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        user.nickname = [UtilHelper getStringValue:[dataDic objectForKey:@"nick"]];
        user.gender = [UtilHelper getStringValue:[dataDic objectForKey:@"gender"]];
        if ([@"F" isEqualToString:user.gender]) {
            user.gender = @"Girl";
        }
        else if ([@"M" isEqualToString:user.gender]) {
            user.gender = @"Boy";
        }
        user.longitude = [UtilHelper getStringValue:[dataDic objectForKey:@"longitude"]];
        user.latitude = [UtilHelper getStringValue:[dataDic objectForKey:@"latitude"]];
        user.avater = [UtilHelper getStringValue:[dataDic objectForKey:@"avater"]];
        user.avater1 = [UtilHelper getStringValue:[dataDic objectForKey:@"avater1"]];
        user.avater2 = [UtilHelper getStringValue:[dataDic objectForKey:@"avater2"]];
        user.exam = [UtilHelper getStringValue:[dataDic objectForKey:@"exam"]];
        NSInteger examType = [user.exam integerValue];
        if (IS_STRING_NOT_EMPTY(user.exam) && examType <= 6 && examType >= 0)
        {
            user.exam = [EXAM_ARRAY objectAtIndex:examType];
        }
        else
        {
            user.exam = @"";
        }
        
        BOOL isTeacher = [[UtilHelper getStringValue:[dataDic objectForKey:@"isTeacher"]] boolValue];
        if (isTeacher)
        {
            user.identity = @"Teacher";
        }
        else
        {
            user.identity = @"Student";
        }
        
        user.applyYear = [UtilHelper getStringValue:[dataDic objectForKey:@"applyYear"]];
        user.testSection = [UtilHelper getStringValue:[dataDic objectForKey:@"section"]];
        user.major = [UtilHelper getStringValue:[dataDic objectForKey:@"major"]];
        
        Match *match = [[Match alloc] init];
        match.matchType = [UtilHelper getStringValue:[dataDic objectForKey:@"filterType"]];
        match.dreamschool = [UtilHelper getStringValue:[dataDic objectForKey:@"dreamSchoolName"]];
        match.examYear = [UtilHelper getStringValue:[dataDic objectForKey:@"examYear"]];
        match.examMonth = [UtilHelper getStringValue:[dataDic objectForKey:@"examMonth"]];
        match.examAddress = [UtilHelper getStringValue:[dataDic objectForKey:@"examAddress"]];
        user.match = match;
        [match release];

        user.lastLogin = [UtilHelper getStringValue:[dataDic objectForKey:@"lastLogin"]];
        user.lastMsg = [UtilHelper getStringValue:[dataDic objectForKey:@"lastMsg"]];
        user.year = [UtilHelper getStringValue:[dataDic objectForKey:@"year"]];
        user.country = [UtilHelper getStringValue:[dataDic objectForKey:@"country"]];
        user.city = [UtilHelper getStringValue:[dataDic objectForKey:@"city"]];
        user.status = [UtilHelper getStringValue:[dataDic objectForKey:@"status"]];
        
        if (_tempUser) {
            RELEASE_SAFELY(_tempUser);
        }
        _tempUser = [user retain];
        
        [self updateUserInfo];
        
        [[UserManager sharedManager].cacheUsers addObject:user];
        [[HTActivityIndicator currentIndicator] hide];
    }
    else {
        [[HTActivityIndicator currentIndicator] displayFailed:@"get user failed!"];
    }
    
}

- (void)getUserInfoFailed:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayFailed:@"get user failed!"];
}


- (void)setUserInfo
{
    _firstHeaderImageView.delegate = self;
    _firstHeaderImageView.enableTapEvent = YES;
    _firstHeaderImageView.tag = 0;
    
    _secondHeaderImageView.delegate = self;
    _secondHeaderImageView.enableTapEvent = YES;
    _secondHeaderImageView.tag = 1;
    
    _thirdHeaderImageView.delegate = self;
    _thirdHeaderImageView.enableTapEvent = YES;
    _thirdHeaderImageView.tag = 2;
    
    if (_isFriendInfo)
    {
        _firstHeaderImageView.enableTapEvent = IS_STRING_NOT_EMPTY(_tempUser.avater);
        _secondHeaderImageView.enableTapEvent = IS_STRING_NOT_EMPTY(_tempUser.avater1);
        _thirdHeaderImageView.enableTapEvent = IS_STRING_NOT_EMPTY(_tempUser.avater2);
        _lookingForBtn.enabled = NO;

    }
    
    UIImage *placeHolderImage = nil;
    if (_isFriendInfo)
    {
        placeHolderImage = ImageNamed(@"photo_card_small.png");
        [_firstHeaderImageView setDefaultImage:placeHolderImage];
        [_secondHeaderImageView setDefaultImage:placeHolderImage];
        [_thirdHeaderImageView setDefaultImage:placeHolderImage];
    }
    else
    {
        if (IS_STRING_EMPTY(_tempUser.avater))
        {
            placeHolderImage = ImageNamed(@"photo_add.png");
        }
        else
        {
            placeHolderImage = ImageNamed(@"photo_card_small.png");
        }
        [_firstHeaderImageView setDefaultImage:placeHolderImage];
        
        if (IS_STRING_EMPTY(_tempUser.avater1))
        {
            placeHolderImage = ImageNamed(@"photo_add.png");
        }
        else
        {
            placeHolderImage = ImageNamed(@"photo_card_small.png");
        }
        [_secondHeaderImageView setDefaultImage:placeHolderImage];
        
        if (IS_STRING_EMPTY(_tempUser.avater1))
        {
            placeHolderImage = ImageNamed(@"photo_add.png");
        }
        else
        {
            placeHolderImage = ImageNamed(@"photo_card_small.png");
        }
        [_thirdHeaderImageView setDefaultImage:placeHolderImage];

    }
    
    [self updateUserInfo];
    
    
}

- (void)updateUserInfo
{
    [_firstHeaderImageView loadImage:_tempUser.avater];
    [_secondHeaderImageView loadImage:_tempUser.avater1];
    [_thirdHeaderImageView loadImage:_tempUser.avater2];
    
    if (_isFriendInfo)
    {
        if ([@"Boy" isEqualToString:_tempUser.gender]) {
            _userTypeImageView.image = [UIImage imageNamed:@"himinfo.png"];
        }
        else if ([@"Girl" isEqualToString:_tempUser.gender]) {
            _userTypeImageView.image = [UIImage imageNamed:@"herinfo.png"];
        }
        else
        {
            _userTypeImageView.image = [UIImage imageNamed:@"himinfo.png"];
        }
    }
    else
    {
        _userTypeImageView.image = [UIImage imageNamed:@"meinfo.png"];
    }

    [self setIdentity];
    if (self.isStudent)
    {        
        _testCategoryLabel.text = @"TEST & APPLY";
        [_applyBtn setTitle:@"Apply year" forState:UIControlStateNormal];
        
        _locationCategoryLabel.text = @"LOCATION & SCHOOL";
        _schoolOrCompanyLabel.text = @"School";
        
//        _locationOrSchoolContainerView.top = 478;
        _schoolOrCompanyTextField.placeholder = @"Enter School";
    }
    else
    {        
        _testCategoryLabel.text = @"TEST & SECTION";
        [_applyBtn setTitle:@"Section" forState:UIControlStateNormal];
        
        _locationCategoryLabel.text = @"LOCATION & COMPANY";
        _schoolOrCompanyLabel.text = @"Company";
        
//        _locationOrSchoolContainerView.top = _lookingForContainerView.top;
        _schoolOrCompanyTextField.placeholder = @"Enter Company";
    }
    
//    _lookingForContainerView.hidden = !self.isStudent;
//    _signatureContainerView.top = _locationOrSchoolContainerView.bottom + 23;
//    
//    _editContainerView.top = _signatureContainerView.bottom - 8;
//    _userInfoContainerScrollView.contentSize = CGSizeMake(_userInfoContainerScrollView.width, _isFriendInfo?_signatureContainerView.bottom + 10:_editContainerView.bottom + 10);
    [self updateContentPosition];
    
    _nickNameLabel.text = _tempUser.nickname;
    _genderLabel.text = [self getPlaceHolderTextWithString:_tempUser.gender isSelectType:YES];
    _ageLabel.text = [self getPlaceHolderTextWithString:_tempUser.year isSelectType:YES];
    _testLabel.text = [self getPlaceHolderTextWithString:_tempUser.exam isSelectType:YES];
    if (self.isStudent)
    {
        _applyYearLabel.text = [self getPlaceHolderTextWithString:_tempUser.applyYear isSelectType:YES];
    }
    else
    {
        _applyYearLabel.text = [self getPlaceHolderTextWithString:_tempUser.testSection isSelectType:YES];

    }
    _cityValueLabel.text = [self getPlaceHolderTextWithString:_tempUser.country isSelectType:NO];
    _schoolOrCompanyValueLabel.text = [self getPlaceHolderTextWithString:_tempUser.city isSelectType:NO];

    if (IS_STRING_NOT_EMPTY(_tempUser.status))
    {
        _signatureTextView.text = _tempUser.status;
    }
    else
    {
        if (_isFriendInfo)
        {
            _signatureTextView.text = @"这是个懒家伙！";
        }
        else
        {
            _signatureTextView.text = @"请填写";
        }

    }
    
    [self updateLookForInfo];
}

- (void)updateContentPosition
{
    if ([@"GRE" isEqualToString:_tempUser.exam])
    {
        _marjoyContainerView.hidden = NO;
        _lookingForContainerView.top = 423;
    }
    else
    {
        _marjoyContainerView.hidden = YES;
        _lookingForContainerView.top = 423 - 24;
    }
    
    _lookingForContainerView.hidden = !self.isStudent;
    
//    _locationOrSchoolContainerView.top = self.isStudent?502:_lookingForContainerView.top;
    _locationOrSchoolContainerView.top = self.isStudent?_lookingForContainerView.bottom + 19:_lookingForContainerView.top;


    _signatureContainerView.top = _locationOrSchoolContainerView.bottom + 23;
    
    _editContainerView.top = _signatureContainerView.bottom - 8;
    _userInfoContainerScrollView.contentSize = CGSizeMake(_userInfoContainerScrollView.width, _isFriendInfo?_signatureContainerView.bottom + 10:_editContainerView.bottom + 10);
    
    _marjoyLabel.text = [self getPlaceHolderTextWithString:_tempUser.major isSelectType:YES];

}

- (NSString *)getPlaceHolderTextWithString:(NSString *)string isSelectType:(BOOL)isSelectType
{
    if (IS_STRING_NOT_EMPTY(string))
    {
        return string;
    }
    
    if (_isFriendInfo)
    {
        return @"未知";
    }
    else
    {
        if (isSelectType)
        {
            return @"请选择";
        }
        else
        {
            return @"请填写";
        }
    }
}

- (void)updateLookForInfo
{
    NSInteger type = 0;
    if (_tempUser.match.matchType)
    {
        type = [_tempUser.match.matchType integerValue];
    }
        
    switch (type)
    {
        case 0:
            if (_isFriendInfo)
            {
                _lookForLabel.text = @"未选择";
            }
            else
            {
                _lookForLabel.text = @"点击并选择";
            }
            break;
        case 1:
//            _lookForLabel.text = [NSString stringWithFormat:@"Dream School：%@",_tempUser.match.dreamschool];
            _lookForLabel.text = @"找自习好友";
            break;
        case 2:
            _lookForLabel.text = @"找Teacher答疑";
            break;
        case 3:
            _lookForLabel.text = [NSString stringWithFormat:@"自助考团：%@-%@，%@",_tempUser.match.examYear,_tempUser.match.examMonth,_tempUser.match.examAddress,nil];
            break;
        default:
            break;
    }}

- (void)setIdentity
{
    if (self.isStudent)
    {
        _studentLabel.alpha = 1;
        _teacherLabel.alpha = 0.5;
        _studentLabel.font = [UIFont boldSystemFontOfSize:15];
        _teacherLabel.font = [UIFont systemFontOfSize:15];
    }
    else
    {
        _studentLabel.alpha = 0.5;
        _teacherLabel.alpha = 1;
        _teacherLabel.font = [UIFont boldSystemFontOfSize:15];
        _studentLabel.font = [UIFont systemFontOfSize:15];
    }
    
    _studentMarkImageView.highlighted = self.isStudent;
    _teacherMarkImageView.highlighted = !self.isStudent;

}


- (void)updatEditStatus
{
    _genderBtn.enabled = _isEditing;
    _ageBtn.enabled = _isEditing;
//    _identityBtn.enabled = _isEditing;
    _testBtn.enabled = _isEditing;
    _applyBtn.enabled = _isEditing;
    _marjoyBtn.enabled = _isEditing;
    _countryTextField.hidden = !_isEditing;
    _schoolOrCompanyTextField.hidden = !_isEditing;
    _locationContainerView.hidden = _isEditing;
    
    _signatureTextView.editable = _isEditing;

//    _lookingForBtn.enabled = _isEditing;
    
    UIColor *backgroundColor = [UIColor clearColor];
    if (_isEditing)
    {
        backgroundColor = RGBACOLOR(0, 0, 0, 0.3);
        
        _countryTextField.text = _tempUser.country;
        _schoolOrCompanyTextField.text = _tempUser.city;
    }    
    _genderBtn.backgroundColor = backgroundColor;
    _ageBtn.backgroundColor = backgroundColor;
//    _identityBtn.backgroundColor = backgroundColor;
    _testBtn.backgroundColor = backgroundColor;
    _applyBtn.backgroundColor = backgroundColor;
    _marjoyBtn.backgroundColor = backgroundColor;
    _signatureTextView.backgroundColor = backgroundColor;
    
    _countryEditBackgroundView.hidden = !_isEditing;
    _schoolOrCompanyEditBgView.hidden = !_isEditing;
    
}


#pragma mark - Set or Get

- (BOOL)isStudent
{
    if ([@"Teacher" isEqualToString:_tempUser.identity])
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

- (NSDictionary *)testCategoryDic
{
    if (_testCategoryDic)
    {
        return _testCategoryDic;
    }
    else
    {
        _testCategoryDic = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Test_Category_list" ofType:@"plist"]];
    }
    
    return _testCategoryDic;
}

#pragma mark -


- (void)receiveMessageNotification
{
    if ([MessageManager sharedManager].newMessageCount > 0) {
        [self.inboxBtn setImage:nil forState:UIControlStateNormal];
        [self.inboxBtn setImage:nil forState:UIControlStateHighlighted];
        [self.inboxBtn setBackgroundImage:[UIImage imageNamed:@"inbox_indicator.png"] forState:UIControlStateNormal];
        [self.inboxBtn setBackgroundImage:[UIImage imageNamed:@"inbox_indicator.png"] forState:UIControlStateHighlighted];
        [self.inboxBtn setTitle:[NSString stringWithFormat:@"%d",[MessageManager sharedManager].newMessageCount] forState:UIControlStateNormal];
    }
    else {
        
        [self.inboxBtn setImage:[UIImage imageNamed:@"inbox_btn.png"] forState:UIControlStateNormal]; 
        [self.inboxBtn setImage:[UIImage imageNamed:@"inbox_btn.png"] forState:UIControlStateHighlighted];        
        [self.inboxBtn setBackgroundImage:nil forState:UIControlStateNormal];
        [self.inboxBtn setBackgroundImage:[UIImage imageNamed:@"tap_light.png"] forState:UIControlStateHighlighted];
        [self.inboxBtn setTitle:nil forState:UIControlStateNormal];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    _userInfoContainerScrollView.top = self.view.height;
    [self receiveMessageNotification];
    
    if (![APP_DELEGATE.touchMaskView isDescendantOfView:self.view])
    {
        [self.view insertSubview:APP_DELEGATE.touchMaskView belowSubview:_sliderBtn];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.5 
                     animations:^{
                         self.backBtn.alpha = 1;
                         self.inboxBtn.alpha = 1;
                         self.friendBtn.alpha = 1;
                         self.userInfoContainerScrollView.top = 0;
                     }];
}

- (void)viewWillDisappear:(BOOL)animated
{  
    [[HTActivityIndicator currentIndicator] hide];
    [super viewWillDisappear:animated];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.backBtn.alpha = 0;
                         self.inboxBtn.alpha = 0;
                         self.friendBtn.alpha = 0;
                     }];
}


- (void)viewDidUnload
{
    [self setBackBtn:nil];
    [self setInboxBtn:nil];
    [self setFriendBtn:nil];
    [self setDataSelectPicker:nil];
    [self setPickContainerView:nil];
    [self setEditBtn:nil];
    [self setNickNameLabel:nil];
    [self setFirstHeaderImageView:nil];
    [self setSecondHeaderImageView:nil];
    [self setThirdHeaderImageView:nil];
    [self setGenderBtn:nil];
    [self setGenderLabel:nil];
    [self setAgeBtn:nil];
    [self setAgeLabel:nil];
    [self setStudentLabel:nil];
    [self setTeacherLabel:nil];
    [self setIdentityBtn:nil];
    [self setTestCategoryLabel:nil];
    [self setTestBtn:nil];
    [self setTestLabel:nil];
    [self setApplyBtn:nil];
    [self setApplyYearLabel:nil];
    [self setLocationCategoryLabel:nil];
    [self setCountryTextField:nil];
    [self setSchoolOrCompanyTextField:nil];
    [self setUserInfoContainerScrollView:nil];
    [self setLookingForContainerView:nil];
    [self setLookingForBtn:nil];
    [self setLookForLabel:nil];
    [self setSignatureContainerView:nil];
    [self setSignatureTextView:nil];
    [self setEditContainerView:nil];
    [self setSchoolOrCompanyLabel:nil];
    [self setCountryEditBackgroundView:nil];
    [self setSchoolOrCompanyEditBgView:nil];
    [self setUserTypeImageView:nil];
    [self setFadeImageView:nil];
    [self setStudentMarkImageView:nil];
    [self setTeacherMarkImageView:nil];
    [self setLocationContainerView:nil];
    [self setCityValueLabel:nil];
    [self setSchoolOrCompanyValueLabel:nil];
    [self setLocationOrSchoolContainerView:nil];
    [self setMarjoyLabel:nil];
    [self setMarjoyContainerView:nil];
    [self setMarjoyBtn:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)tapOnBackBtn:(id)sender {
    if (_isFriendInfo)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}

- (IBAction)tapOnInboxBtn:(id)sender {
    InboxViewController * inboxViewController = [[[InboxViewController alloc] init] autorelease];
    [self.navigationController pushViewController:inboxViewController animated:NO];
}

- (IBAction)tapOnFriendBtn:(id)sender {
    
    BOOL hasNoFilter = NO;
    
    if (IS_STRING_EMPTY([UserManager sharedManager].currentUser.match.matchType) || [@"0" isEqualToString:[UserManager sharedManager].currentUser.match.matchType])
    {
        hasNoFilter = YES;
    }
    
    if (IS_STRING_EMPTY([UserManager sharedManager].currentUser.exam))
    {
        hasNoFilter = YES;
    }
    
    if (![@"Student" isEqualToString:[UserManager sharedManager].currentUser.identity])
    {
        hasNoFilter = YES;
    }

    UIViewController *viewController = nil;
    if (hasNoFilter)
    {
        PeopleNearViewController * peopleNearViewController = [[[PeopleNearViewController alloc] init] autorelease];
        peopleNearViewController.hasNoFilter = YES;
        viewController = peopleNearViewController;
    }
    else
    {
        PeopleDreamSchoolViewController * peopleDreamSchoolViewController = [[[PeopleDreamSchoolViewController alloc] init] autorelease];
        viewController = peopleDreamSchoolViewController;
    }

    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)showAlertViewWithMessage:(NSString *)message
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
    [alertView show];
    [alertView release];
}


- (IBAction)tapOnLogoutBtn:(id)sender {
    [[ITTImageCacheManager sharedManager] clearDiskCache];
    [[ITTImageCacheManager sharedManager] clearMemoryCache];
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"Are you sure logout?" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Logout", nil];
    [alertView show];
    [alertView release];
}

- (IBAction)tapOnUpdateBtn:(id)sender {
    
    _isEditing = YES;
    [self updatEditStatus];
    [self.editBtn setBackgroundImage:[UIImage imageNamed:@"editok_light.png"] forState:UIControlStateHighlighted];
    [self.editBtn setImage:[UIImage imageNamed:@"editok_btn.png"] forState:UIControlStateNormal];
    [self.editBtn setImage:[UIImage imageNamed:@"editok_btn.png"] forState:UIControlStateHighlighted];
    [self.editBtn addTarget:self action:@selector(commitUpdate) forControlEvents:UIControlEventTouchUpInside];
   
}

- (void)commitUpdate
{
    _isEditing = NO;
    [self updatEditStatus];
    
    [self.editBtn setBackgroundImage:[UIImage imageNamed:@"edit_light.png"] forState:UIControlStateHighlighted];
    [self.editBtn setImage:[UIImage imageNamed:@"edit_btn.png"] forState:UIControlStateNormal];
    [self.editBtn setImage:[UIImage imageNamed:@"edit_btn.png"] forState:UIControlStateHighlighted];
    [self.editBtn addTarget:self action:@selector(tapOnUpdateBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    if (!_hasChanged) {
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_tempUser.gender) {
        
        if ([@"Girl" isEqualToString:_tempUser.gender]) {
            
            [params setObject:@"F" forKey:@"gender"];
        }
        else if ([@"Boy" isEqualToString:_tempUser.gender]) {
            
            [params setObject:@"M" forKey:@"gender"];
        }
    }
    if (_tempUser.exam) {
        
        BOOL isHasSelectedExam = NO;
        NSArray *exams = EXAM_ARRAY;
        for (NSString *exam in exams)
        {
            if ([exam isEqualToString:_tempUser.exam])
            {
                NSUInteger index = [exams indexOfObject:exam];
                [params setObject:[NSString stringWithFormat:@"%d",index] forKey:@"exam"];
                isHasSelectedExam = YES;

                break;
            }
        }
        
        if (!isHasSelectedExam)
        {
            [params setObject:@"-1" forKey:@"exam"];
        }
    }
    
    if (_tempUser.year) {
        [params setObject:_tempUser.year forKey:@"year"];
    }
    if (_tempUser.country) {
        [params setObject:_tempUser.country forKey:@"country"];
    }
    if (_tempUser.city) {
        [params setObject:_tempUser.city forKey:@"city"];
    }
    if (_tempUser.dreamSchool) {
        [params setObject:_tempUser.dreamSchool forKey:@"dreamSchool"];
    }
    if (_tempUser.status) {
        [params setObject:_tempUser.status forKey:@"status"];
    }
    
    if (_tempUser.identity)
    {
        if ([@"Teacher" isEqualToString:_tempUser.identity])
        {
//            [params setObject:@"1" forKey:@"isteacher"];
            if (_tempUser.testSection)
            {
                [params setObject:_tempUser.testSection forKey:@"section"];
            }
        }
        else
        {
//            [params setObject:@"0" forKey:@"isteacher"];
            if (_tempUser.applyYear)
            {
                [params setObject:_tempUser.applyYear forKey:@"applyYear"];
            }
        }
    }
    if (_tempUser.major) {
        [params setObject:_tempUser.major forKey:@"major"];
    }

    
    [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUpdateInfo WithParameters:params AndCallBackScope:self AndSuccessSel:@"updateSuccess:" AndFailedSel:@"updateFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Updating..."];
}

- (IBAction)tapOnCancel:(id)sender {
    
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.pickContainerView.top = self.view.height;
                     }];
}

- (IBAction)tapOnConfirmBtn:(id)sender {
    switch (_updateType) {
        case HotWordUpdateDataGender:
        {
            NSString *gender = [GENDER_ARRAY objectAtIndex:[self.dataSelectPicker selectedRowInComponent:0]];
            if (![_genderLabel.text isEqualToString:gender])
            {
                _hasChanged = YES;
                _genderLabel.text = gender;
                _tempUser.gender = gender;
            }
        }
            break;
            
        case HotWordUpdateDataExam:            
        {
            NSString *exam = [EXAM_ARRAY objectAtIndex:[self.dataSelectPicker selectedRowInComponent:0]];
            if (![_testLabel.text isEqualToString:exam])
            {
                if ([@"GRE" isEqualToString:exam] || [@"GRE" isEqualToString:_tempUser.exam])
                {
                    if ([@"GRE" isEqualToString:_tempUser.exam])
                    {
                        _tempUser.major = nil;
                    }
                    _tempUser.exam = exam;
                    [self updateContentPosition];
                }
                
                _hasChanged = YES;
                _testLabel.text = exam;
                _tempUser.exam = exam;
                _tempUser.match = nil;
                _lookForLabel.text = @"点击并选择";
                [self updateLookingForInBackground];
            }
        }

            break;
        case HotWordUpdateDataAge:
        {
            NSString *age = [AGE_ARRAY objectAtIndex:[self.dataSelectPicker selectedRowInComponent:0]];
            if (![_ageLabel.text isEqualToString:age])
            {
                _hasChanged = YES;
                _ageLabel.text = age;
                _tempUser.year = age;
            }
        }
            break;
        case HotWordUpdateDataIdentity:
        {
            NSString *identity = [IDENTITY_ARRAY objectAtIndex:[self.dataSelectPicker selectedRowInComponent:0]];
            if (![_tempUser.identity isEqualToString:identity])
            {
                _hasChanged = YES;
                _tempUser.identity = identity;
                [self setIdentity];
                [self updateUserInfo];
                _schoolOrCompanyTextField.text = @"";
                _schoolOrCompanyValueLabel.text = @"";
                _tempUser.city = @"";
            }
        }

            break;
        case HotWordUpdateDataApplyYear:
        {
            NSString *applyYear = [TEST_YEAR_ARRAY objectAtIndex:[self.dataSelectPicker selectedRowInComponent:0]];
            if (![_applyYearLabel.text isEqualToString:applyYear])
            {
                _hasChanged = YES;
                _applyYearLabel.text = applyYear;
                _tempUser.applyYear = applyYear;
            }
        }
            break;
        case HotWordUpdateDataTestAndSection:
        {
            NSString *exam = [EXAM_ARRAY objectAtIndex:[self.dataSelectPicker selectedRowInComponent:0]];
            if (![_testLabel.text isEqualToString:exam])
            {
                _hasChanged = YES;
                _testLabel.text = exam;
                _tempUser.exam = exam;
            }
            
            NSUInteger selectedRow = [self.dataSelectPicker selectedRowInComponent:0];
            NSArray *testArray = [self.testCategoryDic objectForKey:[EXAM_ARRAY objectAtIndex:selectedRow]];
            
            NSString *testSection = [testArray objectAtIndex:[self.dataSelectPicker selectedRowInComponent:1]];
            if (![_applyYearLabel.text isEqualToString:testSection])
            {
                _hasChanged = YES;
                _applyYearLabel.text = testSection;
                _tempUser.testSection = testSection;
            }
        }
            break;
        default:
            break;
    }
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.pickContainerView.top = self.view.height;
                     }];
}

- (void)updateLookingForInBackground
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_tempUser.match.matchType)
    {
        [params setObject:@"0" forKey:@"type"];
    }
    
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    }
    
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUpdateFilter WithParameters:params AndCallBackScope:self AndSuccessSel:@"updateInBackgroundSuccess:" AndFailedSel:@"updateInBackgroundFailed:"];
}

- (void)updateInBackgroundSuccess:(NSObject *)result
{
    
}

- (void)updateInBackgroundFailed:(NSObject *)result
{
    
}


- (void)updateSuccess:(NSObject *)result
{
    _hasChanged = NO;
    if (![result isKindOfClass:[NSDictionary class]]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Update Failed!"];
        return;
    }
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        [[UserManager sharedManager] saveLoginUser:_tempUser];
        [[HTActivityIndicator currentIndicator] displayMessage:@"Update Succeed!"];
    }
    else {
        
        NSString *error = [UtilHelper getStringValue:[dic objectForKey:@"msg"]];
        [[HTActivityIndicator currentIndicator] displayMessage:error];
    }
    
    [self updateUserInfo];
}

- (void)updateFailed:(NSObject *)result
{
    _hasChanged = NO;
    [[HTActivityIndicator currentIndicator] displayMessage:@"Update Failed!"];
}

#pragma mark ActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) 
    {
        BOOL isCameraAvaible = NO;
        isCameraAvaible = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
        if (!isCameraAvaible) 
        {
            [[HTActivityIndicator currentIndicator] displayMessage:@"No Camera!"];
            return;
        }
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentModalViewController:imagePickerController animated:YES];
        [imagePickerController release];
        
    }
    else if (buttonIndex == 1)
    {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];        
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:imagePickerController animated:YES];
        [imagePickerController release];
    }
}

#pragma mark - ImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info 
{
    
    UIImage *image = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];
//    UIGraphicsBeginImageContext(CGSizeMake(240, 240));
//    [image drawInRect:CGRectMake(0, 0, 240, 240)];
//    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();              
    
    [self dismissModalViewControllerAnimated:YES];
    switch (_headSelectIndex) {
        case 0:
            _firstHeaderImageView.image = image;
            break;
        case 1:
            _secondHeaderImageView.image = image;
            break;
        case 2:
            _thirdHeaderImageView.image = image;
            break;
            
        default:
            break;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    [params setObject:image forKey:@"userfile"];
    [params setObject:[NSString stringWithFormat:@"%d", _headSelectIndex] forKey:@"type"];
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUploadPic WithParameters:params AndCallBackScope:self AndSuccessSel:@"updatePicScuccess:" AndFailedSel:@"updatePicFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Uploading Image..."];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker 
{
    [self dismissModalViewControllerAnimated:YES];
    
}

- (void)updatePicScuccess:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayCompleted:@"Upload Succeed!"];

    NSString *avatorStr = [(NSDictionary *)result objectForKey:@"msg"];
    
    if (!avatorStr || [@"" isEqualToString:avatorStr])
    {
        return;
    }
    
    switch (_headSelectIndex) {
        case 0:
            _tempUser.avater = avatorStr;
            [[ITTImageCacheManager sharedManager] saveImage:_firstHeaderImageView.image withUrl:[IMAGE_BASE_URL stringByAppendingString:avatorStr]];
            break;
        case 1:
            _tempUser.avater1 = avatorStr;
            [[ITTImageCacheManager sharedManager] saveImage:_secondHeaderImageView.image withUrl:[IMAGE_BASE_URL stringByAppendingString:avatorStr]];
            break;
        case 2:
            _tempUser.avater2 = avatorStr;
            [[ITTImageCacheManager sharedManager] saveImage:_thirdHeaderImageView.image withUrl:[IMAGE_BASE_URL stringByAppendingString:avatorStr]];
            break;
            
        default:
            break;
    }
    
    [[UserManager sharedManager] saveLoginUser:_tempUser];
}

- (void)updatePicFailed:(NSObject *)result
{
    
    [[HTActivityIndicator currentIndicator] displayFailed:@"Upload Failed!"];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _activeField = textField;
    
    [UIView animateWithDuration:0.3 animations:^{
        [_userInfoContainerScrollView setContentOffset:CGPointMake(0, _schoolOrCompanyTextField.bottom + _locationOrSchoolContainerView.top - (self.view.height - MAX_KEYBOARD_HEIGHT - 8)) animated:NO];
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{    
    if (textField == _countryTextField)
    {
        if (![_countryTextField.text isEqualToString:_tempUser.country])
        {
            _hasChanged = YES;
            _tempUser.country = _countryTextField.text;
            _cityValueLabel.text = _countryTextField.text;
        }
    }
    else if (textField == _schoolOrCompanyTextField)
    {
        if (![_schoolOrCompanyTextField.text isEqualToString:_tempUser.city])
        {
            _hasChanged = YES;
            _tempUser.city = _schoolOrCompanyTextField.text;
            _schoolOrCompanyValueLabel.text = _schoolOrCompanyTextField.text;
            
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _countryTextField)
    {
        [_schoolOrCompanyTextField becomeFirstResponder];
    }
    else if (textField == _schoolOrCompanyTextField)
    {
        [_signatureTextView becomeFirstResponder];
    }
    
    return YES;
}

#pragma mark - UITextViewDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.3 animations:^{
        [_userInfoContainerScrollView setContentOffset:CGPointMake(0, _editContainerView.bottom - (self.view.height - MAX_KEYBOARD_HEIGHT)) animated:NO];
    }];
    if ([@"请填写" isEqualToString:textView.text])
    {
        textView.text = @"";
    }

}
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (![_signatureTextView.text isEqualToString:_tempUser.status])
    {
        _hasChanged = YES;
        _tempUser.status = _signatureTextView.text;
    }
    
    if ([@"" isEqualToString:textView.text])
    {
        textView.text = @"请填写";
    }


}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([textView.text length] == 140)
    {
        if ([text length] < 1) //用于相应退格事件
        {
            textView.text = [textView.text substringToIndex:[textView.text length] - 1];
        }
        return NO;
    }
    
    if ([@"\n" isEqualToString:text])
    {
        [textView resignFirstResponder];
    }
    
    return YES;
}


-(void)keyboardWillShow:(NSNotification *)aNotification
{
    _userInfoContainerScrollView.contentSize = CGSizeMake(_userInfoContainerScrollView.width,_editContainerView.bottom + 10 + MAX_KEYBOARD_HEIGHT);
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [UIView animateWithDuration:0.3 animations:^{
        _userInfoContainerScrollView.contentSize = CGSizeMake(_userInfoContainerScrollView.width, _editContainerView.bottom + 10);
    }];
}



- (void)showDataPicker
{
    [_activeField resignFirstResponder];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.pickContainerView.bottom = self.view.height;
                     }];

}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{    
    if (self.pickContainerView.top >= self.view.height) {
        
        [self hideKeybord];
    }
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.pickContainerView.top = self.view.height;
                     }];
}

- (void)hideKeybord
{
    [_activeField resignFirstResponder];
    [_signatureTextView resignFirstResponder];
}

- (void)hanldTapGesture:(UIGestureRecognizer *)recognizer
{
    if (self.pickContainerView.top >= self.view.height) {
        
        [self hideKeybord];
    }
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.pickContainerView.top = self.view.height;
                     }];
}


-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIButton class]] || [touch.view isDescendantOfView:self.pickContainerView] || [touch.view isKindOfClass:[UITextView class]]) {
        return NO; 
    }
    return YES;
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (_updateType == HotWordUpdateDataTestAndSection)
    {
        return 2;
    }
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (_updateType)
    {
        case HotWordUpdateDataGender:
            return [GENDER_ARRAY count];
            break;
            
        case HotWordUpdateDataExam:
            return [EXAM_ARRAY count];
            break;
            
        case HotWordUpdateDataAge:
            return [AGE_ARRAY count];
            break;
        case HotWordUpdateDataIdentity:
            return [IDENTITY_ARRAY count];
            break;
        case HotWordUpdateDataApplyYear:
            return [TEST_YEAR_ARRAY count];
            break;
        case HotWordUpdateDataTestAndSection:
            if (component == 0)
            {
                return [EXAM_ARRAY count];
            }
            else
            {
                NSUInteger selectedRow = [pickerView selectedRowInComponent:0];
                NSArray *testArray = [self.testCategoryDic objectForKey:[EXAM_ARRAY objectAtIndex:selectedRow]];
                return [testArray count];
            }
            break;
        default:
            break;
    }
}

#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSArray *dataArray = nil;
    switch (_updateType) {
        case HotWordUpdateDataGender:
//            return [GENDER_ARRAY objectAtIndex:row];
            dataArray = GENDER_ARRAY;
            break;
        case HotWordUpdateDataExam:
//            return [EXAM_ARRAY objectAtIndex:row];
            dataArray = EXAM_ARRAY;
            break;
        case HotWordUpdateDataAge:
//            return [AGE_ARRAY objectAtIndex:row];
            dataArray = AGE_ARRAY;
            break;
        case HotWordUpdateDataIdentity:
//            return [IDENTITY_ARRAY objectAtIndex:row];
            dataArray = IDENTITY_ARRAY;
            break;
        case HotWordUpdateDataApplyYear:
//            return [TEST_YEAR_ARRAY objectAtIndex:row];
            dataArray = TEST_YEAR_ARRAY;
            break;
        case HotWordUpdateDataTestAndSection:
            if (component == 0)
            {
//                return [EXAM_ARRAY objectAtIndex:row];
                dataArray = EXAM_ARRAY;
            }
            else
            {
                NSUInteger selectedRow = [pickerView selectedRowInComponent:0];
                NSArray *testArray = [self.testCategoryDic objectForKey:[EXAM_ARRAY objectAtIndex:selectedRow]];
//                return [testArray objectAtIndex:row];
                dataArray = testArray;
            }
            break;
        default:
            break;
    }
    
    if (row >= [dataArray count])
    {
        return nil;
    }
    return [dataArray objectAtIndex:row];
    
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 0 && _updateType == HotWordUpdateDataTestAndSection)
    {
        [pickerView reloadComponent:1];
    }
}


#pragma mark - LookingForViewControllerDelegate

- (void)lookingForViewController:(LookingForViewController *)viewController didSelectMatch:(Match *)match
{
    _tempUser.match = match;
    [self updateLookForInfo];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_tempUser.match.matchType)
    {
        [params setObject:_tempUser.match.matchType forKey:@"type"];
    }
    
//    if ([@"1" isEqualToString:_tempUser.match.matchType])
//    {
//        if (_tempUser.match.dreamschool)
//        {
//            [params setObject:_tempUser.match.dreamschool forKey:@"dreamschool"];
//        }
//    }
    
    if ([@"3" isEqualToString:_tempUser.match.matchType])
    {
        if (_tempUser.match.examYear)
        {
            [params setObject:_tempUser.match.examYear forKey:@"examyear"];
        }
        if (_tempUser.match.examMonth)
        {
            [params setObject:_tempUser.match.examMonth forKey:@"exammonth"];
        }
        if (_tempUser.match.examAddress)
        {
            [params setObject:_tempUser.match.examAddress forKey:@"examaddress"];
        }

    }

    
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"id"];
    }
    
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeUpdateFilter WithParameters:params AndCallBackScope:self AndSuccessSel:@"updateSuccess:" AndFailedSel:@"updateFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Updating..."];
    
}


#pragma mark - MajorRankingViewControllerDelegate

- (void)majorRankingViewController:(MajorRankingViewController *)viewController didSelectMajor:(NSString *)major
{
    if (![_marjoyLabel.text isEqualToString:major])
    {
        _hasChanged = YES;
        _marjoyLabel.text = major;
        _tempUser.major = major;
    }
}



#pragma mark - IBAction

- (IBAction)tapOnGenderBtn:(id)sender
{
    _updateType = HotWordUpdateDataGender;
    [self.dataSelectPicker reloadAllComponents];
    [self setDefaultPickerSelectRowWithArray:GENDER_ARRAY defaultTitle:_tempUser.gender];
    [self showDataPicker];
}
- (IBAction)tapOnAgeBtn:(id)sender
{
    _updateType = HotWordUpdateDataAge;
    [self.dataSelectPicker reloadAllComponents];
    [self setDefaultPickerSelectRowWithArray:AGE_ARRAY defaultTitle:_tempUser.year];
    [self showDataPicker];
}
- (IBAction)tapOnIdentityBtn:(id)sender
{
    _updateType = HotWordUpdateDataIdentity;
    [self.dataSelectPicker reloadAllComponents];
    [self setDefaultPickerSelectRowWithArray:IDENTITY_ARRAY defaultTitle:_tempUser.identity];
    [self showDataPicker];
}
- (IBAction)tapOnTestBtn:(id)sender
{
    if (self.isStudent)
    {
        _updateType = HotWordUpdateDataExam;
        [self.dataSelectPicker reloadAllComponents];
        [self setDefaultPickerSelectRowWithArray:EXAM_ARRAY defaultTitle:_tempUser.exam];

    }
    else
    {
        _updateType = HotWordUpdateDataTestAndSection;
        [self.dataSelectPicker reloadAllComponents];
        [self setDefaultPickerSelectRowWithArray:EXAM_ARRAY defaultTitle:_tempUser.exam];
        [self setDefaultPickerSelectRowWithDefaultTitle:_tempUser.testSection];
    }
    
    [self showDataPicker];
}
- (IBAction)tapOnApplyBtn:(id)sender
{
    if (self.isStudent)
    {
        _updateType = HotWordUpdateDataApplyYear;
        [self.dataSelectPicker reloadAllComponents];
        [self setDefaultPickerSelectRowWithArray:TEST_YEAR_ARRAY defaultTitle:_tempUser.applyYear];
    }
    else
    {
        _updateType = HotWordUpdateDataTestAndSection;
        [self.dataSelectPicker reloadAllComponents];
        [self setDefaultPickerSelectRowWithArray:EXAM_ARRAY defaultTitle:_tempUser.exam];
        [self setDefaultPickerSelectRowWithDefaultTitle:_tempUser.testSection];
    }
    [self showDataPicker];
}

- (void)setDefaultPickerSelectRowWithArray:(NSArray *)array defaultTitle:(NSString *)defaultTitle
{
    for (NSString *title in array)
    {
        if ([defaultTitle isEqualToString:title])
        {
            [self.dataSelectPicker selectRow:[array indexOfObject:title] inComponent:0 animated:NO];
            break;
        }
    }
}

- (void)setDefaultPickerSelectRowWithDefaultTitle:(NSString *)defaultTitle
{
    NSUInteger selectedRow = [_dataSelectPicker selectedRowInComponent:0];
    NSArray *testArray = [self.testCategoryDic objectForKey:[EXAM_ARRAY objectAtIndex:selectedRow]];
    
    for (NSString *title in testArray)
    {
        if ([defaultTitle isEqualToString:title])
        {
            [self.dataSelectPicker selectRow:[testArray indexOfObject:title] inComponent:1 animated:NO];
            break;
        }
    }
}

- (IBAction)tapOnMarjoyBtn:(id)sender
{
    MajorRankingViewController *majorRankingViewController = [[MajorRankingViewController alloc] init];
    majorRankingViewController.delegate = self;
    [self.navigationController pushViewController:majorRankingViewController animated:YES];
    [majorRankingViewController release];
}



- (IBAction)tapOnLookingForBtn:(id)sender
{
    LookingForViewController *lookingForViewController = [[LookingForViewController alloc] initWithUser:_tempUser];
    lookingForViewController.delegate = self;
    [self.navigationController pushViewController:lookingForViewController animated:YES];
    [lookingForViewController release];
}

- (IBAction)tapOnTalkBtn:(id)sender {
    if ([_tempUser.userId isEqualToString:[UserManager sharedManager].currentUser.userId]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"You can't speak to yourself"];
        return;
    }
    
    ConversationViewController *conversationViewController = [[[ConversationViewController alloc] initWithUser:_tempUser] autorelease];
    [self.navigationController pushViewController:conversationViewController animated:YES];
}

#pragma mark - ITTImageViewDelegate

- (void)imageClicked:(ITTImageView *)imageView
{
    if (_isFriendInfo)
    {
        [self tapOnImageViewWithImageView:imageView];
    }
    else
    {
        _headSelectIndex = imageView.tag;
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"Cancel"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"Camera", @"Photo Library", nil];
        
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
        [actionSheet showInView:self.view.window];
        [actionSheet release];

    }
}

- (void)tapOnImageViewWithImageView:(ITTImageView *)imageView
{
    UIImage *image = nil;
    switch (imageView.tag) {
        case 0:
            image = _firstHeaderImageView.image;
            break;
        case 1:
            image = _secondHeaderImageView.image;
            break;
        case 2:
            image = _thirdHeaderImageView.image;
            break;
            
        default:
            break;
    }
    if (!image) {
        return;
    }
    
    self.enlargeImageView.image = image;
    CGFloat imageHeight = image.size.height/image.size.width * 320;
    self.enlargeImageView.frame = CGRectMake(0, (self.enlargeImageContainer.height - imageHeight) / 2, 320, imageHeight);
    [UIView animateWithDuration:0.3f
                     animations:^{
                         self.enlargeImageContainer.alpha = 1;
                     }
                     completion:^(BOOL finished){
                         UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToDismissImage)] autorelease];
                         [self.enlargeImageContainer addGestureRecognizer:tapGesture];
                     }];
}

- (void)tapToDismissImage
{
    [UIView animateWithDuration:0.3f
                     animations:^{
                         self.enlargeImageContainer.alpha = 0;
                     }
                     completion:^(BOOL finished){
                         for (UITapGestureRecognizer *gesture in self.enlargeImageContainer.gestureRecognizers) {
                             [self.view removeGestureRecognizer:gesture];
                         }
                     }];
}

- (void)checkUpdateUserInfoNotification
{
    BOOL isHasAlert = [USER_DEFAULT boolForKey:@"UpdateUserInfoKey"];
    if (isHasAlert)
    {
        return;
    }
    
    BOOL isAlert = NO;
    if (self.isStudent)
    {
        if ([_tempUser.match.matchType intValue] == 0)
        {
            isAlert = YES;
        }
    }
    else
    {
        if (IS_STRING_EMPTY(_tempUser.testSection))
        {
            isAlert = YES;
        }
    }
    
    if (isAlert)
    {
        [USER_DEFAULT setBool:YES forKey:@"UpdateUserInfoKey"];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"用户信息更新提示" message:@"热词新版本用户信息更丰富，是否立即更新用户信息？" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil];
        alertView.delegate = self;
        alertView.tag = 1;
        [alertView show];
        [alertView release];
    }
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1)
    {
        if (buttonIndex == 1)
        {
            [self tapOnUpdateBtn:nil];
        }
    }
    else
    {
        if (buttonIndex == 1)
        {
            [[UserManager sharedManager] removeLoginUser];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }

    }
}

- (void)dealloc
{
    [_tempUser release];
    [_activeLabel release];
    [_activeField release];
    [_headInfoCell release];
    [_backBtn release];
    [_inboxBtn release];
    [_friendBtn release];
    [_dataSelectPicker release];
    [_pickContainerView release];
    [_editBtn release];
    
    [_nickNameLabel release];
    [_firstHeaderImageView release];
    [_secondHeaderImageView release];
    [_thirdHeaderImageView release];
    [_genderBtn release];
    [_genderLabel release];
    [_ageBtn release];
    [_ageLabel release];
    [_studentLabel release];
    [_teacherLabel release];
    [_identityBtn release];
    [_testCategoryLabel release];
    [_testBtn release];
    [_testLabel release];
    [_applyBtn release];
    [_applyYearLabel release];
    [_locationCategoryLabel release];
    [_countryTextField release];
    [_schoolOrCompanyTextField release];
    [_userInfoContainerScrollView release];
    [_lookingForContainerView release];
    [_lookingForBtn release];
    [_lookForLabel release];
    [_signatureContainerView release];
    [_signatureTextView release];
    [_editContainerView release];
    [_schoolOrCompanyLabel release];
    
    [_testCategoryDic release];
    [_countryEditBackgroundView release];
    [_schoolOrCompanyEditBgView release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_RECEIVE_MESSAGE object:nil];


    [_userTypeImageView release];
    [_fadeImageView release];
    [_studentMarkImageView release];
    [_teacherMarkImageView release];
    [_locationContainerView release];
    [_cityValueLabel release];
    [_schoolOrCompanyValueLabel release];
    [_locationOrSchoolContainerView release];
    [_sliderBtn release];
    [_marjoyLabel release];
    [_marjoyContainerView release];
    [_marjoyBtn release];
    [super dealloc];
}

@end
